<script setup lang="ts">
import { ref, watch } from 'vue'
import Modal from '@/components/common/Modal.vue'
import { uploadApi } from '@/api/upload'

interface Props {
  show: boolean
  currentAvatar?: string
}

interface Emits {
  (e: 'close'): void
  (e: 'update', avatar: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const avatarUrl = ref('')
const previewUrl = ref(props.currentAvatar || '')
const fileInput = ref<HTMLInputElement | null>(null)

// 重置状态
const resetState = () => {
  avatarUrl.value = ''
  previewUrl.value = props.currentAvatar || ''
}

// 监听show变化，重置状态
watch(
  () => props.show,
  (newVal) => {
    if (newVal) {
      resetState()
    }
  },
)

// 处理文件上传
const handleFileChange = async (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]

  if (!file) return

  const validation = uploadApi.validateImage(file)
  if (!validation.valid) {
    alert(validation.message)
    return
  }

  try {
    const response = await uploadApi.uploadFile(file)
    if (response.data.data.fileUrl) {
      previewUrl.value = response.data.data.fileUrl
      avatarUrl.value = response.data.data.fileUrl
    }
  } catch (error) {
    console.error('头像上传失败:', error)
  } finally {
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  }
}

// 处理URL输入
const handleUrlInput = (e: Event) => {
  const input = e.target as HTMLInputElement
  avatarUrl.value = input.value
  previewUrl.value = input.value
}

// 确认更新
const handleConfirm = () => {
  if (avatarUrl.value) {
    emit('update', avatarUrl.value)
  }
}
</script>

<template>
  <Modal :show="show" title="更换头像" @close="emit('close')">
    <div class="p-4">
      <!-- 预览区域 -->
      <div class="mb-6 text-center">
        <div class="w-24 h-24 mx-auto rounded-full overflow-hidden border-2 border-gray-200">
          <img
            :src="previewUrl"
            alt="头像预览"
            class="w-full h-full object-cover"
            @error="previewUrl = '/default-avatar.png'"
          />
        </div>
        <p class="mt-2 text-sm text-gray-500">头像预览</p>
      </div>

      <!-- 上传方式 -->
      <div class="space-y-4">
        <!-- 文件上传 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2"> 从本地上传 </label>
          <div
            class="flex items-center justify-center px-6 py-4 border-2 border-dashed border-gray-300 rounded-lg hover:border-gray-400 cursor-pointer"
            @click="fileInput?.click()"
          >
            <div class="text-center">
              <div class="text-gray-600">点击选择图片</div>
              <p class="mt-1 text-xs text-gray-500">支持 jpg、png 格式，大小不超过 2MB</p>
            </div>
            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              class="hidden"
              @change="handleFileChange"
            />
          </div>
        </div>

        <!-- 图片地址 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2"> 图片地址 </label>
          <input
            type="text"
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="请输入图片URL"
            :value="avatarUrl"
            @input="handleUrlInput"
          />
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="mt-6 flex justify-end space-x-3">
        <button class="px-4 py-2 text-sm text-gray-600 hover:text-gray-800" @click="emit('close')">
          取消
        </button>
        <button
          class="px-4 py-2 text-sm text-white bg-blue-500 rounded-md hover:bg-blue-600"
          @click="handleConfirm"
          :disabled="!avatarUrl"
        >
          确认
        </button>
      </div>
    </div>
  </Modal>
</template>
